package com.gmrz.uas.plugin.dear;

/**
 * Created by gongyuqiang on 2017/5/15.
 */

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by gongyuqiang on 2017/5/15.
 */
public class SmbOperator {
    private static final Logger LOG = LogManager.getLogger(SmbOperator.class);
    protected static boolean isEmpty(String string) {
        return string == null || string.isEmpty();
    }

    protected static String getToken(String host ,String port,String app_id, String app_secret) throws SmbException {
        String access_token = "";
        HashMap<String, Object> hashMap = new HashMap();
        hashMap.put("grant_type", "grant_type");
        hashMap.put("app_id", app_id);
        hashMap.put("app_secret", app_secret);
        String result = "";
        JsonObject json_input = null;
        String url = "http://" + host + ":" + port +"/interface/access/token/get";
        try {
            result = sendHttpData(url, formJsonString(hashMap));
            json_input = (new JsonParser()).parse(result).getAsJsonObject();

            try {
                if(!isEmpty(json_input.get("errcode").toString())) {
                    throw new SmbException(json_input.get("errcode").getAsInt(), json_input.get("errmsg").toString());
                }
            } catch (NullPointerException var6) {
                ;
            }

            access_token = json_input.get("access_token").getAsString();

        } catch (JsonSyntaxException var7) {
            LOG.error("error:" + var7.getMessage());
            throw new SmbException(4007, var7.getMessage());
        }

        return access_token;
    }

    protected static JsonObject getVoiceText(String methodUrl, String token, String voiceprint_id) throws SmbException{
        HashMap<String, Object> hashMap = new HashMap();
        hashMap.put("access_token", token);
        hashMap.put("voiceprint_id", voiceprint_id);
        hashMap.put("text_type", "4097");

        String result = "";
        JsonObject json_input = null;

        try {
            result = sendHttpData(methodUrl, formJsonString(hashMap));
            json_input = (new JsonParser()).parse(result).getAsJsonObject();

            try {
                if(!isEmpty(json_input.get("errcode").toString())) {
                    throw new SmbException(json_input.get("errcode").getAsInt(), json_input.get("errmsg").toString());
                }
            } catch (NullPointerException var6) {
                ;
            }

            return json_input;
        } catch (JsonSyntaxException var7) {
            LOG.error("error:" + var7.getMessage());
            throw new SmbException(4007, var7.getMessage());
        }
    }

    protected static JsonObject removeVoiceprint(String methodUrl, String token, String voiceprint_id) throws SmbException{
        HashMap<String, Object> hashMap = new HashMap();
        hashMap.put("access_token", token);
        hashMap.put("voiceprint_id", voiceprint_id);

        String result = "";
        JsonObject json_input = null;

        try {
            result = sendHttpData(methodUrl, formJsonString(hashMap));
            json_input = (new JsonParser()).parse(result).getAsJsonObject();

            try {
                if(!isEmpty(json_input.get("errcode").toString())) {
                    throw new SmbException(json_input.get("errcode").getAsInt(), json_input.get("errmsg").toString());
                }
            } catch (NullPointerException var) {
                ;
            }

            return json_input;
        } catch (JsonSyntaxException var) {
            LOG.error("error:" + var.getMessage());
            throw new SmbException(4007, var.getMessage());
        }
    }
    protected  static JsonObject getVerifyText(String methodUrl, String token, String voiceprint_id) throws SmbException{
        HashMap<String, Object> hashMap = new HashMap();
        hashMap.put("access_token", token);
        hashMap.put("voiceprint_id", voiceprint_id);
        hashMap.put("text_type", "8193");

        String result = "";
        JsonObject json_input = null;

        try {
            result = sendHttpData(methodUrl, formJsonString(hashMap));
            json_input = (new JsonParser()).parse(result).getAsJsonObject();

            try {
                if(!isEmpty(json_input.get("errcode").toString())) {
                    throw new SmbException(json_input.get("errcode").getAsInt(), json_input.get("errmsg").toString());
                }
            } catch (NullPointerException var6) {
                ;
            }

            return json_input;
        } catch (JsonSyntaxException var7) {
            LOG.error("error:" + var7.getMessage());
            throw new SmbException(4007, var7.getMessage());
        }
    }
    protected static Map<String, Object> StringtoMap(String str) {

        GsonBuilder gb = new GsonBuilder();
        Gson gson = gb.create();
        return gson.fromJson(str, new TypeToken<Map<String,Object>>(){}.getType());
    }


    protected static String formJsonString(Map<String, Object> hashMap) {
        GsonBuilder gb = new GsonBuilder();
        Gson gson = gb.create();
        return gson.toJson(hashMap);
    }

    protected static String sendHttpData(String methodUrl, String strJson) throws SmbException {

        OutputStream outStream = null;
        InputStream is = null;
        HttpURLConnection conn = null;
        try {
            byte[] xmlbyte = strJson.getBytes("UTF-8");
            URL url = new URL(methodUrl);
            LOG.debug("adress:" + url + "   strJson:" + strJson);
            conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Length", String.valueOf(xmlbyte.length));
            conn.setRequestProperty("Content-Type", "text/html; charset=UTF-8");
            conn.setRequestProperty("X-ClientType", "2");

            outStream = conn.getOutputStream();
            outStream.write(xmlbyte);
            outStream.flush();
            LOG.debug("返回码：" + conn.getResponseCode());
            if(conn.getResponseCode() != 200) {
                throw new SmbException(4006, "URL地址错误！");
            } else {
                is = conn.getInputStream();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];

                int len;
                while((len = is.read(buf)) != -1) {
                    out.write(buf, 0, len);
                }

                String string = out.toString("UTF-8");
                out.close();
                LOG.debug("response str:"+string);
                return string;
            }
        } catch (UnsupportedEncodingException var10) {
            LOG.error("sendHttpData error",var10);
            throw new SmbException(4000, var10.getMessage());
        } catch (MalformedURLException var11) {
            LOG.error("sendHttpData error",var11);
            throw new SmbException(4001, var11.getMessage());
        } catch (IOException var13) {
            LOG.error("sendHttpData error",var13);
            throw new SmbException(4002, var13.getMessage());
        }finally{
            try {
                if(null != outStream){
                    outStream.close();
                }
                if(null != is){
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    protected static <T> T transStringToMap(String mapString, Class<T> beanCalss) {
        Gson gson  = new Gson();
        T bean = gson.fromJson(mapString, beanCalss);
        return bean;
    }

    protected static boolean isConnectError(Map<String, Object> map) {
        Iterator it = map.entrySet().iterator();
        boolean temp = false;

        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            if("errcode".equals(entry.getKey().toString())) {
                temp = true;
                break;
            }
        }

        return temp;
    }

    protected String doFilePost(String methodUrl, Map<String, String> map, Map<String, File> files) throws IOException {
        String BOUNDARY = "----WebKitFormBoundaryDwvXSRMl0TBsL6kW";
        URL url = new URL(methodUrl);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setConnectTimeout(30000);
        connection.setReadTimeout(30000);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("Charsert", "UTF-8");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        OutputStream out = new DataOutputStream(connection.getOutputStream());
        byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();
        Map.Entry entry;
        Iterator var10;
        if(files != null && !files.isEmpty()) {
            var10 = files.entrySet().iterator();

            while(var10.hasNext()) {
                entry = (Map.Entry)var10.next();
                File file = (File)entry.getValue();
                String fileName = (String)entry.getKey();
                StringBuilder sb = new StringBuilder();
                sb.append("--");
                sb.append(BOUNDARY);
                sb.append("\r\n");
                sb.append("Content-Disposition: form-data;name=\"" + fileName + "\";filename=\"" + file.getName() + "\"\r\n");
                sb.append("Content-Type:application/octet-stream");
                byte[] data = sb.toString().getBytes();
                out.write(data);
                DataInputStream in = new DataInputStream(new FileInputStream(file));
                int bytes = 0;
                byte[] bufferOut = new byte[1024];

                while((bytes = in.read(bufferOut)) != -1) {
                    out.write(bufferOut, 0, bytes);
                }

                out.write("\r\n".getBytes());
                in.close();
            }
        }

        if(map != null && !map.isEmpty()) {
            var10 = map.entrySet().iterator();

            while(var10.hasNext()) {
                entry = (Map.Entry)var10.next();
                StringBuilder sb = new StringBuilder();
                sb.append("--");
                sb.append(BOUNDARY);
                sb.append("\r\n");
                sb.append("Content-Disposition: form-data; name=\"" + (String)entry.getKey() + "\"");
                sb.append("\r\n");
                sb.append("\r\n");
                sb.append((String)entry.getValue());
                sb.append("\r\n");
                byte[] data = sb.toString().getBytes();
                out.write(data);
            }
        }

        out.write(end_data);
        out.flush();
        out.close();
        if(connection.getResponseCode() == 200) {
            InputStream inStream = connection.getInputStream();
            byte[] number = read(inStream);
            String json = new String(number);
            return json;
        } else {
            return null;
        }
    }

    protected static byte[] read(InputStream inStream) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        boolean var3 = false;

        int len;
        while((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }

        inStream.close();
        return outStream.toByteArray();
    }

    protected static String upLoadvoice(String methodUrl, String parameter, byte[] voice) {
        String BOUNDARY = "----------HV2ymHFg03ehbqgZCaKO6jyH";
        InputStream is = null;
        DataInputStream dis = null;
        String line = null;

        String var16;
        try {
            HashMap hashMap;
            try {
                URL url = new URL(methodUrl);
                HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                connection.setConnectTimeout(30000);
                connection.setReadTimeout(30000);
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("Charset", "UTF-8");
                connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
                StringBuffer contentBody = new StringBuffer("--" + BOUNDARY);
                String endBoundary = "\r\n--" + BOUNDARY + "--\r\n";
                connection.connect();
                OutputStream out = connection.getOutputStream();
                contentBody.append("\r\n").append("Content-Disposition: form-data; name=\"").append("123\"").append("\r\n").append("\r\n").append(parameter).append("\r\n").append("--").append(BOUNDARY);
                String boundaryMessage1 = contentBody.toString();
                out.write(boundaryMessage1.getBytes("utf-8"));
                contentBody = new StringBuffer();
                contentBody.append("\r\n").append("Content-Disposition:form-data; name=\"").append("123\"; ").append("filename=\"").append("123\"").append("\r\n").append("Content-Type:application/octet-stream").append("\r\n\r\n");
                String boundaryMessage2 = contentBody.toString();
                out.write(boundaryMessage2.getBytes("utf-8"));
                out.write(voice, 0, voice.length);
                contentBody.append("------------HV2ymHFg03ehbqgZCaKO6jyH");
                out.write("------------HV2ymHFg03ehbqgZCaKO6jyH--\r\n".getBytes("UTF-8"));
                out.write(endBoundary.getBytes("utf-8"));
                out.flush();
                out.close();
                is = connection.getInputStream();
                dis = new DataInputStream(is);
                line = dis.readLine();
                return line;
            } catch (MalformedURLException var31) {
                hashMap = new HashMap();
                hashMap.put("errcode", Integer.valueOf(4001));
                hashMap.put("errmsg", var31.getMessage());
                var16 = formJsonString(hashMap);
                return var16;
            } catch (ProtocolException var32) {
                hashMap = new HashMap();
                hashMap.put("errcode", Integer.valueOf(4003));
                hashMap.put("errmsg", var32.getMessage());
                var16 = formJsonString(hashMap);
            } catch (IOException var34) {
                hashMap = new HashMap();
                hashMap.put("errcode", Integer.valueOf(4002));
                hashMap.put("errmsg", var34.getMessage());
                var16 = formJsonString(hashMap);
                return var16;
            }
        } finally {
            try {
                is.close();
                dis.close();
            } catch (IOException var30) {
                HashMap<String, Object> hashMap = new HashMap();
                hashMap.put("errcode", Integer.valueOf(4002));
                hashMap.put("errmsg", var30.getMessage());
                return formJsonString(hashMap);
            }
        }

        return var16;
    }
}
